package com.example.mybatisplusdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.mybatisplusdemo.mapper.ProductMapper;
import com.example.mybatisplusdemo.model.domain.Cart;
import com.example.mybatisplusdemo.mapper.CartMapper;
import com.example.mybatisplusdemo.model.domain.Product;
import com.example.mybatisplusdemo.model.dto.UserCartProductDTO;
import com.example.mybatisplusdemo.service.ICartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lqj
 * @since 2025-06-30
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;


    @Override
    public List<UserCartProductDTO> getCartByUserId(Long userId) {
        return cartMapper.selectCartDetailsByUserId(userId);
    }

    @Override
    public boolean addToCart(Long userId, Long productId, BigDecimal quantity) {
        // 检查商品是否存在和库存
        Product product = productMapper.selectById(productId);
        if (product == null || product.getDeleted()) {
            throw new RuntimeException("商品不存在或已下架");
        }
        // 转换库存为BigDecimal进行比较
        BigDecimal inventory = BigDecimal.valueOf(product.getInventory() != null ? product.getInventory() : Long.MAX_VALUE);

        if (inventory.compareTo(quantity) < 0) {
            throw new RuntimeException("库存不足");
        }

        // 检查是否已存在购物车记录
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId, userId)
                .eq(Cart::getProductId, productId)
                .eq(Cart::getDeleted, false);

        Cart existingCart = this.getOne(queryWrapper);

        if (existingCart != null) {
            // 检查总数量是否超过库存
            BigDecimal totalQuantity = new BigDecimal(String.valueOf(existingCart.getQuantity())).add(quantity);
            if (inventory.compareTo(totalQuantity) < 0) {
                throw new RuntimeException("超过库存限制");
            }

            existingCart.setQuantity(totalQuantity);
            existingCart.setUpdateTime(LocalDateTime.now());
            return this.updateById(existingCart);
        } else {
            // 新增记录
            Cart newCart = new Cart();
            newCart.setUserId(userId);
            newCart.setProductId(productId);
            newCart.setQuantity(quantity);
            newCart.setDeleted(false);
            newCart.setCreateTime(LocalDateTime.now());
            newCart.setUpdateTime(LocalDateTime.now());
            return this.save(newCart);
        }
    }
}
